<template>
	<uni-popup type="bottom" ref="popupDialogObj">
		<view v-if="isSimple">
			<simple-picker-date
				v-if="ifShowComp"
				ref="simplePickerObj"
				@onCancel="onCancel"
				@onConfirm="onConfirm" 
				:defaultValue="defaultDate" 
				:themeColor="themeColor"
				:startDate="startDate"
				:title="title"
				:endDate="endDate">
			</simple-picker-date>
		</view>
		<view v-else>
			<view class="title_bar">
				<view style="width: 180rpx"><text class="cancel_text" :style="'color:'+themeColor" @click="close">取消</text></view>
				<text class="title_text" v-if="isMultiple">{{title}}{{checkedList && checkedList.length > 0 ? '(已选'+checkedList.length+'天)':'(可选多天)'}}</text>
				<text class="title_text" v-else>{{title}}</text>
				<view style="width: 180rpx">
					<text v-if="!isSimple" class="clean_text" :style="'color:red'" @click="clean">清空</text>
					<text v-if="!isSimple" space="emsp" class="divider_text"> | </text>
					<text class="cancel_text" :style="'color:'+themeColor" @click="comfirmModel">确定</text></view>
			</view>
			<view class="uni_flex_row_align_left year_month_bar">
				<text class="year_text">{{year}}年</text>
				<uni-icons type="back" @click="prveMonth" size="18"></uni-icons>
				<text class="title_date" decode>{{&nbsp;}}{{month < 10 ? '0'+month:month}}月{{&nbsp;}}</text>
				<uni-icons v-if="isAbleSelectFutureDate ? true : ((year < curYear) || (month < curMonth && year === curYear))" type="forward" @click="nextMonth" size="18"></uni-icons>
			</view>		
			<next-calendar
				v-if="ifShowComp"
				ref="calendarObj"
				:mode="isMultiple ? 'multiple':'single'"
				:isAbleSelectFutureDate="isAbleSelectFutureDate"
				:selected="checkedList"
				:lunar="true" 
				:themeColor="themeColor"
				:clearDate="false"
				:showMonth="showMonthOnCenter"
				:isShowHeader="false"
				@change="checkedEvent"
			 />
		</view>
	</uni-popup>
</template>

<script>
	import nextCalendar from './next-calendar.vue';
	import simplePickerDate from './simple-pickerdate.vue';
	
	function getNowDate() {
		let date = new Date();
		let year = date.getFullYear();
		let month = date.getMonth() + 1;
		let day = date.getDate();
		if (month.toString().length == 1) {
			month = "0" + month;
		}
		if (day.toString().length == 1) {
			day = "0" + day;
		}
		return year + "-" + month + "-" + day;
	}
	
	export default {
		components:{ nextCalendar,simplePickerDate },
		// 日期选择完成
		emits:['finishSelectDate'],
		props: {
			// 是否默认选中今日
			checkedToady:{
				type:Boolean,
				default:false
			},
			// 默认选中的日期列表(可用于传入之前选择的值)
			defaultCheckedList:{
				type: Array,
				default:()=>{
					return []
				}
			},
			mode: {
				type: String,
				default: 'simple'
			},
			// 是否可以选择未来日期
			isAbleSelectFutureDate:{
				type: Boolean,
				default: true
			},
			// 是否在日历中间显示大大的月份数字
			showMonthOnCenter:{
				type: Boolean,
				default: true
			},
			// 主题风格颜色
			themeColor:{
				type: String,
				default: '#f9ae3d'
			},
			// 弹窗的标题文字
			title:{
				type: String,
				default: '选择日期'
			},
			startDate: {	
				type: String,
				default () {
					return "1971-01-01"
				}
			},
			endDate: {
				type: String,
				default () {
					return "2099-12-31"
				}
			},
			defaultDate: {
				type: String,
				default () {
					return getNowDate()
				}
			}		
		},
		data() {
			return {
				checkedList:[],
				year:2022,
				month:7,
				curYear:2022,
				curMonth:6,
				ifShowComp: false,
			}
		},
		computed: {
			isSimple() {
				return this.mode === 'simple'
			},
			isMultiple() {
				return this.mode === 'multiple'
			},
			isRange() {
				return this.mode === 'range'
			}
		},
		methods: {
			init () {
				let date = new Date();
				this.month = date.getMonth() + 1;
				this.year = date.getFullYear();
				this.date = date.getDate();
				
				this.curYear = this.year;
				this.curMonth = this.month;
				
				setTimeout(() => {
					if (!this.isSimple) {	
						const cale = this.$refs.calendarObj.cale
						const dateStr = ''+this.year+'-'+(this.month < 10 ? '0'+this.month:this.month)+'-'+(this.date < 10 ? '0'+this.date:this.date);
						if(this.isMultiple || this.isRange){
							this.checkedList = []
							if(this.defaultCheckedList){
								this.defaultCheckedList.forEach((item,index)=>{
									this.checkedList.push({date: cale.getDate(item).fullDate});
								})
							}
							if(this.checkedToady){
								this.checkedList.push({date:dateStr});
							}
						} else {
							if(this.checkedToady){
								this.checkedList = [{date:dateStr}];
							} else if (this.defaultCheckedList && this.defaultCheckedList.length) {
								this.checkedList = [{date:cale.getDate(this.defaultCheckedList[0]).fullDate}]
							}
						}
					}
				})	
			},
			onCancel(){
				this.close();
			},
			onConfirm(date){
				this.close();
				this.$emit("finishSelectDate",[ date.dateValue]);
			},
			updateCheckedList(list){
				this.checkedList = list || [];
			},
			comfirmModel(){
				const list = (this.checkedList || []).map(item => item.date)
				this.$emit("finishSelectDate",list);
				this.close();
			},
			getCheckedList(){
				return this.checkedList || [];
			},
			prveMonth(){
				if(this.month === 1){
					this.year -= 1;
					this.month = 12;
				}else{
					this.month -= 1;
				}
				this.$refs.calendarObj.pre();
			},
			nextMonth(){
				if(this.month === 12){
					this.year += 1;
					this.month = 1;
				}else{
					this.month += 1;
				}
				this.$refs.calendarObj.next();
			},
			getDatesBetween(startDateStr, endDateStr) {
			  var startDate = new Date(startDateStr);
			  var endDate = new Date(endDateStr);
			  
			  // 确保起始日期早于或等于结束日期
			  if (startDate > endDate) {
			    var temp = startDate;
			    startDate = endDate;
			    endDate = temp;
			  }
			  
			  var dates = [];
			  var currentDate = startDate;
			  
			  while (currentDate <= endDate) {
			    dates.push(currentDate.toISOString().split('T')[0]);
			    currentDate.setDate(currentDate.getDate() + 1);
			  }	  
			  return dates;
			},
			checkedEvent(week){
				if(this.isRange) { // 区间
					if(this.checkedList.length > 1) {
						this.checkedList.length = 0;
						this.checkedList.push({date: week.fulldate});
					} else {
						const index = this.checkedList.findIndex(item => item.date === week.fulldate)
						if(index !== -1) {
							this.checkedList.splice(index, 1)
						} else if(this.checkedList.length === 0) {
							this.checkedList.push({date: week.fulldate});
						} else {
							const dateList = this.getDatesBetween(this.checkedList[0].date, week.fulldate);
							this.checkedList = dateList.map(dateStr => ({date: dateStr}));
						}
					}
					
				} else if (this.isMultiple) {	// 多选
					const index = this.checkedList.findIndex(item => item.date === week.fulldate)
					if (index !== -1) {
						this.checkedList.splice(index, 1)
					} else {
						this.checkedList.push({date: week.fulldate})
					}
				} else {	// 单选
					let temp = [{date: week.fulldate}];
					this.checkedList = temp;			
				}
			},
			open() {
				this.ifShowComp = true;
				
				setTimeout(() => {
					// #ifndef MP
					let date = new Date();
					this.month = date.getMonth() + 1;
					this.year = date.getFullYear();
					this.date = date.getDate();
					
					this.curYear = this.year;
					this.curMonth = this.month;
					// #endif
					this.init();
					this.$refs.popupDialogObj.open();
				})	
			},
			clean() {
				this.checkedList = []
			},
			close() {
				this.$refs.popupDialogObj.close();
				setTimeout(() => {
					this.ifShowComp = false;
				})
			},
		}
	}
</script>

<style>
@import url('next-date-picker.css');
</style>
